package com.iss.card.view.overrideview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

public class SlideViewGroup extends ViewGroup {

	Scroller scroller;

	public SlideViewGroup(Context context) {
		super(context);
		init(context);
	}

	public SlideViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public SlideViewGroup(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context ct) {
		scroller = new Scroller(ct);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int count = getChildCount();
		for (int i = 0; i < count; i++) {
			if (i == 0 && count > 1) {
				getChildAt(i).measure(
						MeasureSpec.makeMeasureSpec(getChildAt(i)
								.getMeasuredWidth(), MeasureSpec.EXACTLY),
						heightMeasureSpec);
				measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
			} else {
				getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
			}
		}
		scrollTo(getChildAt(0).getMeasuredWidth(), 0);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childCount = getChildCount();
		int childLeft = 0;
		for (int i = 0; i < childCount; i++) {
			View childView = getChildAt(i);
			int width = childView.getMeasuredWidth();
			childView.layout(childLeft, 0, childLeft + width,
					childView.getMeasuredHeight());
			childLeft += width;
		}
	}

	/**
	 * slide view and let the side menu view show or hide. in scroller there are
	 * 2 children, one is side menu view in (0, 0) and the other is content view
	 * in (content view.width, 0).
	 * 
	 * @return true means show side menu view and false means hide side menu
	 *         view.
	 */
	public boolean toggle() {
		if (getScrollX() == 0) {
			scroller.startScroll(0, 0, getChildAt(0).getMeasuredWidth(), 0);
			return false;
		} else {
			scroller.startScroll(0, 0, 0, 0);
			return true;
		}
	}

	@Override
	public void computeScroll() {
		super.computeScroll();
		if (scroller.computeScrollOffset()) {
			scrollTo(scroller.getCurrX(), scroller.getCurrY());
		}
	}
}
